package net.blogways.ordermgr.util;


import org.apache.commons.chain.Context;

import java.util.List;
import java.util.Map;

/**
 * dataTable 的分页和排序.
 *
 * @author chenxin
 * created on  2018/3/6
 */
public class DataTableArrangement {

  public StringBuffer DataTableArrangement(StringBuffer sql, Context context, Map params) {
    StringBuffer str = new StringBuffer();
    str.append("SELECT datatable.* FROM( \n")
        .append(sql)
        .append(" ) datatable WHERE 1=1 ");

    if (context.containsKey("selectList")) {
      List<Map> selectList = (List) context.get("selectList");
      for (Map selectMap : selectList) {
        String columsName = (String) selectMap.get("columsName");
        String columsValue = (String) selectMap.get("columsValue");
        if(columsName.indexOf("|1")!=-1){
          columsName=columsName.substring(0,columsName.length()-2);
          str.append(" AND datatable.").append(columsName).append(" = :V" + columsName);
          params.put("V" + columsName,columsValue);
        }else{
          str.append(" AND datatable.").append(columsName).append(" LIKE BINARY :V" + columsName);
          params.put("V" + columsName, "%" + columsValue + "%");
        }


      }
    }

//    str.append(" AND datatable.LAST_NAME LIKE BINARY '%超%'");

    String orderName = (String) context.getOrDefault("orderName", null);
    String orderDir = (String) context.getOrDefault("orderDir", null);
    if (orderName != null && !orderName.equals("")) {
      str.append(" ORDER BY datatable.").append(orderName).append(" ").append(orderDir);
    }

    String start = (String) context.getOrDefault("start", null);
    String length = (String) context.getOrDefault("length", null);
    if (start != null && !length.equals("")) {
      str.append(" LIMIT ").append(start).append(" , ").append(Integer.valueOf(start) + Integer.valueOf(length));
    }

    return str;
  }
}
